package io.github.biezhi.elves.examples;

import java.util.List;
import java.util.stream.Collectors;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import io.github.biezhi.elves.Elves;
import io.github.biezhi.elves.config.Config;
import io.github.biezhi.elves.pipeline.Pipeline;
import io.github.biezhi.elves.request.Request;
import io.github.biezhi.elves.response.Response;
import io.github.biezhi.elves.response.Result;
import io.github.biezhi.elves.spider.Spider;
import lombok.extern.slf4j.Slf4j;

public class ZhiHuExample {
	static final String redir = "https://www.douban.com/people/144537495/";
	static final String login = "https://www.douban.com/accounts/login";
	
	//输入用户名及密码
    String form_email="";
    String form_password="";
	
	@Slf4j
	static class ZhiHuSpider extends Spider {
		public ZhiHuSpider(String name) {
			super(name);
			this.startUrls(redir);
		}

		@Override
		public void onStart(Config config) {
			this.addPipeline((Pipeline<List<String>>) (item, request) -> log.info("保存到文件: {}", item));
		}

		public Result parse(Response response) {
			Result<List<String>> result = new Result<>();
			Elements elements = response.body().css("#content table .pl2 a");

			List<String> titles = elements.stream().map(Element::text).collect(Collectors.toList());
			result.setItem(titles);

			// 获取下一页 URL
			Elements nextEl = response.body().css("#content > div > div.article > div.paginator > span.next > a");
			if (null != nextEl && nextEl.size() > 0) {
				String nextPageUrl = nextEl.get(0).attr("href");
				Request nextReq = this.makeRequest(nextPageUrl, this::parse);
				result.addRequest(nextReq);
			}
			return result;
		}

	}

	public static void main(String[] args) {
		ZhiHuSpider zhiHuSpider = new ZhiHuSpider("豆瓣电影");
		Elves.me(zhiHuSpider, Config.me()).start();
	}
}
